/*
 * Copyright (c) 2021 Talkweb Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "ohos_errno.h"
#include "iot_adc.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"

#define TASK_STACK_SIZE 4096
#define TASK_PRIO 25
#define ADC_VOLTAGE_GPIO 5

static void AdcVoltageTask(void)
{
    float voltage;
    unsigned short val;
    unsigned int ret;

    IoTGpioInit(ADC_VOLTAGE_GPIO);
    IoSetPull(ADC_VOLTAGE_GPIO, IOT_IO_PULL_NONE);
    printf("----- Enter AdcVoltageTask -----\r\n");
    for (;;)
    {
        //获取ADC采集值
        ret = IoTAdcRead(IOT_ADC_CHANNEL_2, &val, IOT_ADC_EQU_MODEL_8, IOT_ADC_CUR_BAIS_DEFAULT, 256);
        if (ret != EC_SUCCESS)
        {
            printf("Failed to read adc! Err code = %d\n", ret);
            continue;
        }

        //将ADC采集值转换成电压值
        voltage = IOTAdcConvertToVoltage(val);
        printf("voltage:%.3fV \r\n", voltage);

        usleep(1000000);
    }
}

static void AdcVoltageExample(void)
{
    osThreadAttr_t attr;
    attr.name = "AdcVoltageTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = TASK_STACK_SIZE;
    attr.priority = TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)AdcVoltageTask, NULL, &attr) == NULL)
    {
        printf("[thinkgo] Falied to create AdcVoltageTask!\n");
    }
    return;
}

APP_FEATURE_INIT(AdcVoltageExample);
